//
//  ForgetPwdViewController.m
//  GBKTrade
//
//  Created by LionIT on 13/03/2018.
//  Copyright © 2018 LionIT. All rights reserved.
//

#import "GSForgetPwdVC.h"
#import "SZForgetPwdViewModel.h"
#import "SZSecurityCodeViewModel.h"
#import "NSString+Helper.h"
#import "RegisterTextField.h"

@interface GSForgetPwdVC ()
@property (nonatomic,strong) UIButton* confirmButton;
@property (nonatomic,strong) UIButton* saoButton;
@property (nonatomic,strong) SZForgetPwdViewModel* viewModel;
@property (nonatomic,strong) SZSecurityCodeViewModel* securityCodeViewModel;

@property (nonatomic,strong) RegisterTextField* passwordTx;
@property (nonatomic,strong) RegisterTextField* againPasswordTx;
@property (nonatomic,strong) RegisterTextField* phoneTx;
@property (nonatomic,strong) RegisterTextField* codeTx;

@property (nonatomic, strong) NSTimer *timers;
@property (nonatomic, assign) NSInteger second;//读秒

@end

@implementation GSForgetPwdVC

- (instancetype)init
{
    self = [super init];
    if (self) {
        self.view.backgroundColor=MainBackgroundColor;
        [self setSubviews];
        [self addActions];
    }
    return self;
}
- (SZForgetPwdViewModel *)viewModel{
    
    if (!_viewModel) {
        _viewModel=[SZForgetPwdViewModel new];
    }
    
    return _viewModel;
}

-(SZSecurityCodeViewModel *)securityCodeViewModel{
    if (!_securityCodeViewModel) {
        _securityCodeViewModel=[SZSecurityCodeViewModel new];
        _securityCodeViewModel.securityCodeType=SZSecurityCodeViewTypeFindLoginPassword;
    }
    
    return _securityCodeViewModel;
    
}
- (void)viewDidLoad {
    [super viewDidLoad];
    [self setNeedsStatusBarAppearanceUpdate];
    [self.btnLeft setImage:YQ_IMAGE(@"nav_back_white") forState:UIControlStateNormal];
}

-(void)setSubviews{
    
    [self setTitleText:NSLocalizedString(@"忘记密码", nil)];
    [self setValue:@(NSTextAlignmentCenter) forKeyPath:@"_txtTitle.textAlignment"];
    
    RegisterTextField* phoneTx=[RegisterTextField new];
    phoneTx.placeholder=NSLocalizedString(@"请输入手机号码", nil);
    phoneTx.textColor=[UIColor blackColor];
    phoneTx.font=[UIFont systemFontOfSize:14.0f];
    self.phoneTx=phoneTx;
    [self.view addSubview:phoneTx];
    [phoneTx mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(NavigationStatusBarHeight);
        make.left.mas_equalTo(FIT(15));
        make.width.mas_equalTo(ScreenWidth-FIT(15)*2);
        make.height.mas_equalTo(FIT(60));
    }];
    
    RegisterTextField* passwordTx=[RegisterTextField new];
    passwordTx.placeholder=NSLocalizedString(@"请输入新密码", nil);
    passwordTx.textColor=[UIColor blackColor];
    passwordTx.font=[UIFont systemFontOfSize:14.0f];
    passwordTx.isShowTextBool = YES;
    [passwordTx setSecureTextEntry:YES];
    
    self.passwordTx=passwordTx;
    [self.view addSubview:passwordTx];
    [passwordTx mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(phoneTx.mas_bottom);
        make.left.mas_equalTo(FIT(15));
        make.width.mas_equalTo(ScreenWidth-FIT(15)*2);
        make.height.mas_equalTo(FIT(60));
    }];
    
    
    
    RegisterTextField* againPasswordTx=[RegisterTextField new];
    againPasswordTx.placeholder=NSLocalizedString(@"请再次输入密码", nil);
    againPasswordTx.textColor=[UIColor blackColor];
    againPasswordTx.font=[UIFont systemFontOfSize:14.0f];
    [againPasswordTx setSecureTextEntry:YES];
    againPasswordTx.isShowTextBool = YES;
    [self.view addSubview:againPasswordTx];
    self.againPasswordTx=againPasswordTx;
    [againPasswordTx mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(passwordTx.mas_bottom);
        make.left.mas_equalTo(FIT(15));
        make.width.mas_equalTo(ScreenWidth-FIT(15)*2);
        make.height.mas_equalTo(FIT(60));
    }];
    
    
    
  
    
    
    RegisterTextField* codeTx=[RegisterTextField new];
    codeTx.placeholder=NSLocalizedString(@"请输入验证码", nil);
    codeTx.textColor=[UIColor blackColor];
    codeTx.font=[UIFont systemFontOfSize:14.0f];
    [self.view addSubview:codeTx];
    self.codeTx=codeTx;
    [codeTx mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(againPasswordTx.mas_bottom);
        make.left.mas_equalTo(FIT(15));
        make.width.mas_equalTo(ScreenWidth-FIT(15)*2);
        make.height.mas_equalTo(FIT(60));
    }];
    
    
    
    UIButton* saoButton=[UIButton new];
    self.saoButton=saoButton;
    [self.saoButton.titleLabel setFont:[UIFont systemFontOfSize:14.0f]];
    [self.saoButton.titleLabel setTextAlignment:NSTextAlignmentCenter];
    [self.saoButton setTitle:NSLocalizedString(@"发送", nil) forState:UIControlStateNormal];
    [self.saoButton setTitleColor:MainThemeColor forState:UIControlStateNormal];
    [self.view addSubview:saoButton];
    [self.saoButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.mas_equalTo(codeTx.mas_centerY);
        make.right.mas_equalTo(-FIT(30));
    }];
    
    
    self.confirmButton=[UIButton new];
    [self.confirmButton.titleLabel setFont:[UIFont systemFontOfSize:14.0f]];
    [self.confirmButton.titleLabel setTextAlignment:NSTextAlignmentCenter];
    [self.confirmButton setTitle:NSLocalizedString(@"确定", nil) forState:UIControlStateNormal];
    [self.confirmButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [self.confirmButton setBackgroundImage:YQ_IMAGE(@"btnImg") forState:UIControlStateNormal];
    
    [self.view addSubview:self.confirmButton];
    [self.confirmButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(codeTx.mas_bottom).offset(FIT(40));
        make.left.mas_equalTo(FIT3(48));
        make.right.mas_equalTo(FIT3(-48));
        make.height.mas_equalTo(FIT3(150));
    }];
    [self.confirmButton setGradientBackGround];
//    [self.confirmButton setBackgroundImage:[UIImage imageWithColor:UIColorFromRGB(0x00b500)] forState:UIControlStateSelected];
    [self.confirmButton setCircleBorderWidth:FIT(1) bordColor:[UIColor clearColor] radius:FIT(2)];

}

-(void)addActions{
    
    @weakify(self);
    [self.viewModel.successSignal subscribeNext:^(id x) {
        @strongify(self);
        
        [LCProgressHUD showMessage:@"修改成功"];
       
        [[SZSundriesCenter instance] delayExecutionInMainThread:^{
            [self.navigationController popViewControllerAnimated:YES];
        }];
        
    }];
    [self.viewModel.failureSignal subscribeNext:^(id x) {
        @strongify(self);
        [LCProgressHUD showFailure:x];

    }];
    
//    [[self.confirmButton rac_signalForControlEvents:UIControlEventTouchUpInside]subscribeNext:^(id x) {
//        @strongify(self);
//
//        if (isEmptyString(self.phoneTx.text)) {
//            [LCProgressHUD showMessage:@"请输入手机号码"];
//            return ;
//        }else if (isEmptyString(self.codeTx.text)){
//            [LCProgressHUD showMessage:@"请输入验证码"];
//        }else if ([self.passwordTx.text length] == 0) {
//            [LCProgressHUD showMessage:@"请输入登录密码"];
//            return;
//        }else if ([self.againPasswordTx.text length] == 0) {
//            [LCProgressHUD showMessage:@"请再次输入登录密码"];
//            return;
//        }
//        else if (![[self.againPasswordTx.text trim] isEqualToString:[self.passwordTx.text trim]]) {
//            [LCProgressHUD showMessage:@"密码不一致,请重新输入"];
//            return;
//        }else if(self.passwordTx.text.length < 6 || self.passwordTx.text.length > 16){
//            [LCProgressHUD showMessage:@"请输入6-16位字母+数字组合"];
//            return ;
//        }else if (self.passwordTx.text.length >= 6) {
//            NSString * regex = @"^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{6,16}$";
//            NSPredicate *pred = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", regex];
//            BOOL result = [pred evaluateWithObject:self.passwordTx.text];
//            if (!result) {
//                [LCProgressHUD showMessage:@"请输入6-16位字母+数字组合"];
//                return ;
//            }
//        }
//    }];
    
    
        [[self.confirmButton rac_signalForControlEvents:UIControlEventTouchUpInside]subscribeNext:^(id x) {
            
            if (isEmptyString(self.phoneTx.text)) {
                [LCProgressHUD showMessage:@"请输入手机号码"];
                return ;
            }
            
            if ([self.passwordTx.text length] == 0) {
                [LCProgressHUD showMessage:@"请输入登录密码"];
                return;
            }
            
            if ([self.againPasswordTx.text length] == 0) {
                [LCProgressHUD showMessage:@"请再次输入登录密码"];
                return;
            }
            
            if (![[self.againPasswordTx.text trim] isEqualToString:[self.passwordTx.text trim]]) {
                [LCProgressHUD showMessage:@"密码不一致,请重新输入"];
                return;
            }
            
            if(self.passwordTx.text.length < 6 || self.passwordTx.text.length > 16){
                [LCProgressHUD showMessage:@"请输入6-16位字母+数字组合"];
                return ;
            }else if (self.passwordTx.text.length >= 6) {
                NSString * regex = @"^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{6,16}$";
                NSPredicate *pred = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", regex];
                BOOL result = [pred evaluateWithObject:self.passwordTx.text];
                if (!result) {
                    [LCProgressHUD showMessage:@"请输入6-16位字母+数字组合"];
                    return ;
                }
            }
            
            if (isEmptyString(self.codeTx.text)) {
                [LCProgressHUD showMessage:@"请输入验证码"];
                return ;
            }
            
            NSDictionary *dict = @{@"phoneNum":self.phoneTx.text,
                                  @"password":[AppUtil md5:self.passwordTx.text],
                                   @"messageCode":self.codeTx.text,
                                   @"countryCode":@"86"
                                  };
            NSString *urlStr = [NSString stringWithFormat:@"%@users/forgetPassword",BaseHttpUrl];
            [[SZHTTPSRsqManager sharedSZHTTPSRsqManager] postRequestWithUrlString:urlStr appendParameters:nil bodyParameters:dict successBlock:^(id responseObject) {
                if ([responseObject[@"code"] integerValue] == 0) {
                    [LCProgressHUD showSuccess:@"修改成功"];
                    [self.navigationController popViewControllerAnimated:YES];
                }else {
                    [LCProgressHUD showMessage:responseObject[@"msg"]];
                }
            } failureBlock:^(NSError *error) {

            }];
        
        
    }];
        
    [self.securityCodeViewModel.successSignal subscribeNext:^(id x) {
        @strongify(self);
        [LCProgressHUD showFailure:x];
    }];
    
    [self.securityCodeViewModel.failureSignal subscribeNext:^(id x) {
        @strongify(self);
        [LCProgressHUD showFailure:x];
    }];
    
    
    //验证码
    WeakSelf(self);
    [[self.saoButton rac_signalForControlEvents:UIControlEventTouchUpInside]subscribeNext:^(id x) {
        NSDictionary *paraters = @{@"msgType":@"2",
                                   @"phoneNum":self.phoneTx.text,
                                   @"countryCode":@"86"
                                   };
        NSString *urlStr = [NSString stringWithFormat:@"%@users/validationMsg",BaseHttpUrl];
        [SZHTTPSReqManager postRequestWithUrlString:urlStr appendParameters:nil bodyParameters:paraters successBlock:^(id responseObject) {
            if ([responseObject[@"code"] integerValue] == 0) {
                [LCProgressHUD showSuccess:@"发送成功"];
                //点击之后倒计时
                weakSelf.second = 59;
                weakSelf.timers = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(timeFieMethod) userInfo:nil repeats:YES];
            }else {
                [LCProgressHUD showFailure:responseObject[@"msg"]];
            }
        } failureBlock:^(NSError *error) {
            
        }];
        
    }];
    
}

- (void)timeFieMethod {
    [self.saoButton setTitle:[NSString stringWithFormat:@"%ld",_second] forState:UIControlStateNormal];
    _second--;
    if (_second == 0) {
        [_timers invalidate];
        [self.saoButton setTitle:@"发送" forState:UIControlStateNormal];
    }
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}


@end

